# Redis推送服务
import time

import redis
import json
import logging
from typing import Dict, Any, Optional
import base64


class RedisPublisher:
    """Redis消息发布器"""

    def __init__(self, redis_config: Dict[str, Any]):
        """
        初始化Redis发布器
        Args:
            redis_config: Redis配置
        """
        self.config = redis_config['redis']
        self.channels = redis_config['channels']

        try:
            self.redis_client = redis.Redis(
                host=self.config['host'],
                port=self.config['port'],
                db=self.config['db'],
                password=self.config['password'],
                decode_responses=True
            )

            # 测试连接
            self.redis_client.ping()
            logging.info("Redis连接成功")

        except Exception as e:
            logging.error(f"Redis连接失败: {e}")
            self.redis_client = None

    def publish_frame(self, frame_data: str, detections: list) -> bool:
        """
        发布处理后的帧数据
        Args:
            frame_data: base64编码的帧数据
            detections: 检测结果
        Returns:
            发布是否成功
        """
        if not self.redis_client:
            return False

        try:
            message = {
                'timestamp': time.time(),
                'frame_data': frame_data,
                'detections': detections
            }

            # 发布到帧通道
            self.redis_client.publish(
                self.channels['frame_channel'],
                json.dumps(message)
            )

            return True

        except Exception as e:
            logging.error(f"发布帧数据失败: {e}")
            return False

    def publish_detection_results(self, detections: list) -> bool:
        """
        发布检测结果
        Args:
            detections: 检测结果列表
        Returns:
            发布是否成功
        """
        if not self.redis_client:
            return False

        try:
            message = {
                'timestamp': time.time(),
                'detections': detections,
                'detection_count': len(detections)
            }

            # 发布到检测结果通道
            self.redis_client.publish(
                self.channels['detection_channel'],
                json.dumps(message)
            )

            return True

        except Exception as e:
            logging.error(f"发布检测结果失败: {e}")
            return False

    def close(self):
        """关闭Redis连接"""
        if self.redis_client:
            self.redis_client.close()
            logging.info("Redis连接已关闭")
